#!/usr/bin/python2
# -*- coding: UTF-8 -*-

import logging
import urllib2
import urllib
import sys
import os
import re
import json
import codecs
import copy
import time
from sys import argv

from baidumap_api.baidu_map import BaiduMap
from cvsparser import CvsParser

def logConf(is_debug, file_name):
    if is_debug:
        logging.basicConfig(level=logging.DEBUG,
            format='%(asctime)s %(filename)s+%(lineno)d [%(levelname)s] %(message)s', filemode='w')
    else:
        logging.basicConfig(level=logging.INFO,
            format='%(asctime)s %(filename)s+%(lineno)d [%(levelname)s] %(message)s',
            filename=file_name,
            filemode='w')

def getSysTime():
    time_tuple = time.localtime(time.time())  # 获取当前的时间返回一个时间元组
    fmt = '%Y%m%d-%H%M%S'  # 格式化时间
    return time.strftime(fmt, time_tuple)  # 把传入的元组按照格式，输出字符串

def getConf(config_file, key):
    file_lines = []
    try:
        file_cfg = open(config_file, "r")
        file_lines = file_cfg.readlines()
        file_cfg.close()
    except Exception, err:
        logging.error(err)
        return None

    for line in file_lines:
        word_array = line.split('=')
        if len(word_array) != 2:
            logging.error('read config %s failed', config_file)
            return None

        if word_array[0] == key:
            return word_array[1]

    return None

def doTest():
    config_file = './config/baidumap.ini'
    baidu_key = getConf(config_file, 'baidu_key')
    if not baidu_key:
        logging.error('load config file failed, %s', config_file)
        return

    city = '广州'
    query_key = '商务大厦'

    logging.info('Startup baidu nap query system, city=%s, query=%s', city, query_key)

    baidu_map = BaiduMap(baidu_key)
    count, titles, recording_list = baidu_map.query_baidu_map(city, query_key, 3)

is_test = True

def main():
    # init logger
    curr_time = getSysTime()
    if curr_time > "20170922-000000":
        return

    log_file = "baidusearch-" + curr_time + ".log"
    if len(sys.argv) >= 4 and sys.argv[len(sys.argv) - 1] == "debug":
        logConf(True, log_file)
    else:
        logConf(True, log_file)

    if is_test:
        doTest()
        return

    if len(sys.argv) < 3:
        logging.error('len(sys.argv)=%u, input argement error, example: baidumap_main.py city key1 key2 key3', len(sys.argv))
        return

    config_file = './config/baidumap.ini'
    baidu_key = getConf(config_file, 'baidu_key')
    if not baidu_key:
        logging.error('load config file failed, %s', config_file)
        return

    city = sys.argv[1]
    query_key = sys.argv[2]
    try:
        for i in range(3, len(sys.argv)):
            query_key = query_key + "$" + sys.argv[i]
    except Exception, error:
        logging.error('parser input argement error: %s', error)
        return

    logging.info('Startup baidu nap query system, city=%s, query=%s', city, query_key)

    baidu_map = BaiduMap(baidu_key)
    cvs_parser = CvsParser()
    count, titles, recording_list = baidu_map.query_baidu_map(city, query_key, 3)
    file_name = city + "-" + query_key + "-" + curr_time + ".csv"
    cvs_parser.open(file_name, titles)
    cvs_parser.writeRows(recording_list)
    # cvs_parser.close()

    logging.info('Recording count = %d, save result to %s', count, file_name)
    logging.info('Exit baidu map query system')

if __name__ == "__main__":
    main()
else:
    pass